package com.edu.framework.websocket.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.net.URI;
import java.util.Map;

public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
            attributes.put("token", servletServerHttpRequest.getServletRequest().getParameter("token"));
            String code = getCode(servletServerHttpRequest);
            attributes.put("code",code);
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    private String getCode(ServletServerHttpRequest request){
        URI uri = request.getURI();
        String query = uri.getQuery();
        String code = query.substring(query.indexOf("=")+1);
        return code;
    }
}
